﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Net;
using System.IO;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;

namespace DotNet.Utilities
{
    public class ImagePJ
    {
        public Bitmap Im;

        private Bitmap[] bitmaplist = new Bitmap[4];
        private Bitmap[] bitmaplist2 = new Bitmap[4];

        public CookieContainer cookie;

        public ImagePJ(string url)
        {
            Im = new Bitmap( GetImageFormUrl(url, false));
        }

        public ImagePJ()
        {

        }

        public ImagePJ(string url, bool hascookie)
        {
            Im = new Bitmap( GetImageFormUrl(url, hascookie));
        }

        public ImagePJ(Image image)
        {
            Im = new Bitmap(image); 
        }

        public ImagePJ(Bitmap bm)
        {
            Im = bm;
        }

        /// <summary>
        /// get image url from url 
        /// </summary>
        /// <param name="url"></param>
        /// <param name="hascookie"></param>
        /// <returns></returns>
        private Image GetImageFormUrl(string url,bool hascookie)
        {
            cookie = null;
            if (hascookie)
                cookie = new CookieContainer();

            Stream s = DotNet.Utilities.HttpHelper.GetStream(url, cookie, null,Encoding.Default);
            Image reimg = Image.FromStream(s);
            return reimg;
        }

        /// <summary>
        /// get gray value
        /// </summary>
        /// <param name="posClr"></param>
        /// <returns></returns>
        private int GetGrayNumColor(System.Drawing.Color posClr)
        {
            return (posClr.R * 19595 + posClr.G * 38469 + posClr.B * 7472) >> 16;
        }

        /// <summary>
        /// 黑白图片
        /// </summary>
        public void Whitleandblack()
        {
            GrayByPixels();

          
            for (int i = 0; i < Im.Width; i++)
            {
                for (int j = 0; j < Im.Height; j++)
                {
                    Color c = Im.GetPixel(i, j);
                    if (c.R > 150)
                    {
                        Im.SetPixel(i, j, Color.FromArgb(255, 255, 255));
                    }

                }
            }

            for (int i = 0; i < Im.Width; i++)
            {
                for (int j = 0; j < Im.Height; j++)
                {
                    Color c = Im.GetPixel(i, j);
                    if (c.R != 255)
                    {
                        Im.SetPixel(i, j, Color.FromArgb(0, 0, 0));
                    }

                }
            }

        }

        public bool HasBlack(int row, Bitmap bmp)
        {
            for (int i = 0; i < bmp.Height; i++)
            {
                if (bmp.GetPixel(row, i).R != 255)
                    return true;

            }
            return false;
        }

        public bool HasBlack2(int col, Bitmap bmp)
        {
            if (col == bmp.Height)
                return false;
            for (int i = 0; i < bmp.Width; i++)
            {
                if (bmp.GetPixel(i, col).R != 255)
                    return true;

            }
            return false;
        }

        /// <summary>
        /// 得到最后要验证的图片
        /// </summary>
        private void GetResultBitmap()
        {
            if (bitmaplist[0] != null)
            {
                int startindex = 0;
                int endindex = 0;
                for (int i = 0; i < bitmaplist[0].Height; i++)
                {
                    if (HasBlack2(i, bitmaplist[0]))
                    {
                        startindex = i;
                        break;
                    }
                }

                for (int j = startindex; j <= bitmaplist[0].Height; j++)
                {
                    if (!HasBlack2(j, bitmaplist[0]))
                    {
                        endindex = j;
                        break;
                    }
                    if (j == bitmaplist[0].Height)
                        endindex = j;
                }

                bitmaplist2[0] = bitmaplist[0].Clone(new Rectangle(0, startindex, bitmaplist[0].Width, endindex - startindex), System.Drawing.Imaging.PixelFormat.Format32bppArgb);

    
            }

            if (bitmaplist[1] != null)
            {
                int startindex = 0;
                int endindex = 0;
                for (int i = 0; i < bitmaplist[1].Height; i++)
                {
                    if (HasBlack2(i, bitmaplist[1]))
                    {
                        startindex = i;
                        break;
                    }
                }

                for (int j = startindex; j <= bitmaplist[1].Height; j++)
                {
                    if (!HasBlack2(j, bitmaplist[1]))
                    {
                        endindex = j;
                        break;
                    }
                    if (j == bitmaplist[1].Height)
                        endindex = j;
                }

                bitmaplist2[1] = bitmaplist[1].Clone(new Rectangle(0, startindex, bitmaplist[1].Width, endindex - startindex), System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            }

            if (bitmaplist[2] != null)
            {
                int startindex = 0;
                int endindex = 0;
                for (int i = 0; i < bitmaplist[2].Height; i++)
                {
                    if (HasBlack2(i, bitmaplist[2]))
                    {
                        startindex = i;
                        break;
                    }
                }

                for (int j = startindex; j <= bitmaplist[2].Height; j++)
                {
                    if (!HasBlack2(j, bitmaplist[2]))
                    {
                        endindex = j;
                        break;
                    }
                    if (j == bitmaplist[2].Height)
                        endindex = j;
                }

                bitmaplist2[2] = bitmaplist[2].Clone(new Rectangle(0, startindex, bitmaplist[2].Width, endindex - startindex), System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            }

            if (bitmaplist[3] != null)
            {
                int startindex = 0;
                int endindex = 0;
                for (int i = 0; i < bitmaplist[3].Height; i++)
                {
                    if (HasBlack2(i, bitmaplist[3]))
                    {
                        startindex = i;
                        break;
                    }
                }

                for (int j = startindex; j <= bitmaplist[3].Height; j++)
                {
                    if (!HasBlack2(j, bitmaplist[3]))
                    {
                        endindex = j;
                        break;
                    }
                    if (j == bitmaplist[3].Height)
                        endindex = j;
                }

                bitmaplist2[3] = bitmaplist[3].Clone(new Rectangle(0, startindex, bitmaplist[3].Width, endindex - startindex), System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            }
        }


        public string GetResult()
        {
            if (Im != null)
            {
                Whitleandblack();
                Split(0, 0, Im);
                GetResultBitmap();
                return Analysis(bitmaplist2[0]) + Analysis(bitmaplist2[1]) +
                 Analysis(bitmaplist2[2]) + Analysis(bitmaplist2[3]);
            }
            return null;
        }

        /// <summary>
        /// 分析
        /// </summary>
        /// <param name="bmp"></param>
        /// <returns></returns>
        public string Analysis(Bitmap bmp)
        {
            int blackcount = 0;
            blackcount = GetBlackCountRow(bmp, 0);

            double temp = Convert.ToDouble(blackcount) / Convert.ToDouble(bmp.Width);

            blackcount = 0;
            if (temp > 0.75)// 5, 7
            {

                temp = GetBlackColCount(bmp, bmp.Width / 2);
                if (temp > 2)
                {
                    return "5";
                }
                else
                {
                    return "7";
                }
            }

            blackcount = GetBlackCountRow(bmp, bmp.Height - 1);
            temp = Convert.ToDouble(blackcount) / Convert.ToDouble(bmp.Width);

            if (temp >= 0.75)//1 ,2
            {
                blackcount = GetBlackCountcol(bmp, bmp.Width / 2);
                temp = Convert.ToDouble(blackcount) / Convert.ToDouble(bmp.Height);
                blackcount = GetBlackCountcol(bmp, bmp.Width / 2 - 1);
                double temp2 = Convert.ToDouble(blackcount) / Convert.ToDouble(bmp.Height);
                blackcount = GetBlackCountcol(bmp, bmp.Width / 2 + 1);
                double temp3 = Convert.ToDouble(blackcount) / Convert.ToDouble(bmp.Height);

                if (temp2 > 0.8 || temp > 0.8 || temp3 > 0.8)
                {
                    return "1";
                }
                else
                {
                    return "2";
                }
            }

            blackcount = GetBlackCountRow(bmp, bmp.Height / 2 + 1);
            temp = Convert.ToDouble(blackcount) / Convert.ToDouble(bmp.Width);
            blackcount = GetBlackCountRow(bmp, bmp.Height / 2 + 2);
            double temp4 = Convert.ToDouble(blackcount) / Convert.ToDouble(bmp.Width);
            blackcount = GetBlackCountRow(bmp, bmp.Height / 2 + 3);
            double temp5 = Convert.ToDouble(blackcount) / Convert.ToDouble(bmp.Width);
            if (temp > 0.9 || temp4 > 0.9 || temp5 > 0.9)
            {
                return "4";
            }

            blackcount = GetBlackCountcol(bmp, bmp.Width / 2);
            temp = Convert.ToDouble(bmp.Width - blackcount) / Convert.ToDouble(bmp.Width);
            blackcount = GetBlackColCount(bmp, bmp.Width / 2);
            if (temp >= 0.45 && blackcount < 3)
                return "0";

            blackcount = GetBlackRowCount(bmp, bmp.Height / 4);
            int blackcount2 = GetBlackRowCount(bmp, bmp.Height * 3 / 4);
            int blackcount3 = GetBlackRowCount(bmp, bmp.Height * 2 / 3);

            if (blackcount == 1 && blackcount == 1 && blackcount3 == 1)
                return "3";
            else if (blackcount == 1 && blackcount == 2 && blackcount3 == 2)
                return "6";
            else if (blackcount == 2 && blackcount2 == 2)
                return "8";
            else if (blackcount == 2 && blackcount2 == 1)
                return "9";
            return "6";
        }

        /// <summary>
        /// split
        /// </summary>
        /// <param name="pos"></param>
        /// <param name="start"></param>
        /// <param name="bmp"></param>
        private void Split(int pos, int start, Bitmap bmp)
        {
            int startindex = 0;
            int endinex = 0;
            if (pos > 3)
                return;
            if (start > bmp.Width)
                return;

            for (int i = start; i < bmp.Width; i++)
            {
                if (HasBlack(i, bmp))
                {
                    startindex = i;
                    break;
                }
            }

            for (int j = startindex; j < bmp.Width; j++)
            {
                if (!HasBlack(j, bmp))
                {
                    endinex = j;
                    break;
                }
            }

            if (endinex - startindex <= 0 || endinex - startindex > 12)
                endinex = startindex + 10;

            bitmaplist[pos] = bmp.Clone(new Rectangle(startindex, 0, endinex - startindex, bmp.Height), System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            pos++;
            Split(pos, endinex, bmp);

        }

        /// <summary>
        /// Change Gray by pixel
        /// </summary>
        public void GrayByPixels()
        {
            for (int i = 0; i < Im.Height; i++)
            {
                for (int j = 0; j < Im.Width; j++)
                {
                    int tmpValue = GetGrayNumColor(Im.GetPixel(j, i));
                    Im.SetPixel(j, i, Color.FromArgb(tmpValue, tmpValue, tmpValue));
                }
            }
        }


        /// <summary>
        /// clear border
        /// </summary>
        /// <param name="borderWidth"></param>
        public void ClearPicBorder(int borderWidth)
        {
            for (int i = 0; i < Im.Height; i++)
            {
                for (int j = 0; j < Im.Width; j++)
                {
                    if (i < borderWidth || j < borderWidth || j > Im.Width - 1 - borderWidth || i > Im.Height - 1 - borderWidth)
                        Im.SetPixel(j, i, Color.FromArgb(255, 255, 255));
                }
            }
        }


        /// <summary>
        /// change gray by line
        /// </summary>
        public void GrayByLine()
        {
            Rectangle rec = new Rectangle(0, 0, Im.Width, Im.Height);
            BitmapData bmpData = Im.LockBits(rec, ImageLockMode.ReadWrite, Im.PixelFormat);// PixelFormat.Format32bppPArgb);
        
            IntPtr scan0 = bmpData.Scan0;
            int len = Im.Width * Im.Height;
            int[] pixels = new int[len];
            Marshal.Copy(scan0, pixels, 0, len);

            //对图片进行处理
            int GrayValue = 0;
            for (int i = 0; i < len; i++)
            {
                GrayValue = GetGrayNumColor(Color.FromArgb(pixels[i]));
                pixels[i] = (byte)(Color.FromArgb(GrayValue, GrayValue, GrayValue)).ToArgb();      //Color转byte
            }

            Im.UnlockBits(bmpData);
        }

        /// </summary>
        /// <param name="dgGrayValue">灰度背景分界值</param>
        /// <param name="CharsCount">有效字符数</param>
        /// <returns></returns>
        public void GetPicValidByValue(int dgGrayValue, int CharsCount)
        {
            int posx1 = Im.Width; int posy1 = Im.Height;
            int posx2 = 0; int posy2 = 0;
            for (int i = 0; i < Im.Height; i++)      //找有效区
            {
                for (int j = 0; j < Im.Width; j++)
                {
                    int pixelValue = Im.GetPixel(j, i).R;
                    if (pixelValue < dgGrayValue)     //根据灰度值
                    {
                        if (posx1 > j) posx1 = j;
                        if (posy1 > i) posy1 = i;

                        if (posx2 < j) posx2 = j;
                        if (posy2 < i) posy2 = i;
                    };
                };
            };
            // 确保能整除
            int Span = CharsCount - (posx2 - posx1 + 1) % CharsCount;   //可整除的差额数
            if (Span < CharsCount)
            {
                int leftSpan = Span / 2;    //分配到左边的空列 ，如span为单数,则右边比左边大1
                if (posx1 > leftSpan)
                    posx1 = posx1 - leftSpan;
                if (posx2 + Span - leftSpan < Im.Width)
                    posx2 = posx2 + Span - leftSpan;
            }
            //复制新图
            Rectangle cloneRect = new Rectangle(posx1, posy1, posx2 - posx1 + 1, posy2 - posy1 + 1);
            Im = Im.Clone(cloneRect, Im.PixelFormat);
        }

        /// 得到有效图形,图形为类变量
        /// </summary>
        /// <param name="dgGrayValue">灰度背景分界值</param>
        /// <param name="CharsCount">有效字符数</param>
        /// <returns></returns>
        public void GetPicValidByValue(int dgGrayValue)
        {
            int posx1 = Im.Width; int posy1 = Im.Height;
            int posx2 = 0; int posy2 = 0;
            for (int i = 0; i < Im.Height; i++)      //找有效区
            {
                for (int j = 0; j < Im.Width; j++)
                {
                    int pixelValue = Im.GetPixel(j, i).R;
                    if (pixelValue < dgGrayValue)     //根据灰度值
                    {
                        if (posx1 > j) posx1 = j;
                        if (posy1 > i) posy1 = i;

                        if (posx2 < j) posx2 = j;
                        if (posy2 < i) posy2 = i;
                    };
                };
            };
            //复制新图
            Rectangle cloneRect = new Rectangle(posx1, posy1, posx2 - posx1 + 1, posy2 - posy1 + 1);
            Im = Im.Clone(cloneRect, Im.PixelFormat);
        }

        /// <summary>
        /// 得到有效图形,图形由外面传入
        /// </summary>
        /// <param name="dgGrayValue">灰度背景分界值</param>
        /// <param name="CharsCount">有效字符数</param>
        /// <returns></returns>
        public Bitmap GetPicValidByValue(Bitmap singlepic, int dgGrayValue)
        {
            int posx1 = singlepic.Width; int posy1 = singlepic.Height;
            int posx2 = 0; int posy2 = 0;
            for (int i = 0; i < singlepic.Height; i++)      //找有效区
            {
                for (int j = 0; j < singlepic.Width; j++)
                {
                    int pixelValue = singlepic.GetPixel(j, i).R;
                    if (pixelValue < dgGrayValue)     //根据灰度值
                    {
                        if (posx1 > j) posx1 = j;
                        if (posy1 > i) posy1 = i;

                        if (posx2 < j) posx2 = j;
                        if (posy2 < i) posy2 = i;
                    };
                };
            };
            //复制新图
            Rectangle cloneRect = new Rectangle(posx1, posy1, posx2 - posx1 + 1, posy2 - posy1 + 1);
            return singlepic.Clone(cloneRect, singlepic.PixelFormat);
        }

        /// <summary>
        /// 平均分割图片
        /// </summary>
        /// <param name="RowNum">水平上分割数</param>
        /// <param name="ColNum">垂直上分割数</param>
        /// <returns>分割好的图片数组</returns>
        public Bitmap[] GetSplitPics(int RowNum, int ColNum)
        {
            if (RowNum == 0 || ColNum == 0)
                return null;
            int singW = Im.Width / RowNum;
            int singH = Im.Height / ColNum;
            Bitmap[] PicArray = new Bitmap[RowNum * ColNum];

            Rectangle cloneRect;
            for (int i = 0; i < ColNum; i++)      //找有效区
            {
                for (int j = 0; j < RowNum; j++)
                {
                    cloneRect = new Rectangle(j * singW, i * singH, singW, singH);
                    PicArray[i * RowNum + j] = Im.Clone(cloneRect, Im.PixelFormat);//复制小块图
                }
            }
            return PicArray;
        }

        /// <summary>
        /// 返回灰度图片的点阵描述字串，1表示灰点，0表示背景
        /// </summary>
        /// <param name="singlepic">灰度图</param>
        /// <param name="dgGrayValue">背前景灰色界限</param>
        /// <returns></returns>
        public string GetSingleBmpCode(Bitmap singlepic, int dgGrayValue)
        {
            Color piexl;
            string code = "";
            for (int posy = 0; posy < singlepic.Height; posy++)
                for (int posx = 0; posx < singlepic.Width; posx++)
                {
                    piexl = singlepic.GetPixel(posx, posy);
                    if (piexl.R < dgGrayValue)    // Color.Black )
                        code = code + "1";
                    else
                        code = code + "0";
                }
            return code;
        }


        /// <summary>
        /// 计算图像的直方图
        /// </summary>
        /// <param name="img"></param>
        /// <returns></returns>
        public int[] GetHisogram(Bitmap img,int length)
        {

            BitmapData data = img.LockBits(new System.Drawing.Rectangle(0, 0, img.Width, img.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);

            int[] histogram = new int[256];

            unsafe
            {

                byte* ptr = (byte*)data.Scan0;

                int remain = data.Stride - data.Width * 3;

                for (int i = 0; i < histogram.Length; i++)

                    histogram[i] = 0;

                for (int i = 0; i < data.Height; i++)
                {

                    for (int j = 0; j < data.Width; j++)
                    {

                        int mean = ptr[0] + ptr[1] + ptr[2];

                        mean /= 3;

                        histogram[mean]++;

                        ptr += 3;

                    }

                    ptr += remain;

                }

            }

            img.UnlockBits(data);

            return histogram;

        }

        /// <summary>
        /// 计算相减后的绝对值
        /// </summary>
        /// <param name="firstNum"></param>
        /// <param name="secondNum"></param>
        /// <returns></returns>
        public float GetAbs(int firstNum, int secondNum)
        {

            float abs = Math.Abs((float)firstNum - (float)secondNum);

            float result = Math.Max(firstNum, secondNum);

            if (result == 0)

                result = 1;

            return abs / result;

        }

        /// <summary>
        /// 最后结果
        /// </summary>
        /// <param name="firstNum"></param>
        /// <param name="scondNum"></param>
        /// <returns></returns>
        public float GetResult(int[] firstNum, int[] scondNum)
        {

            if (firstNum.Length != scondNum.Length)
            {

                return 0;

            }

            else
            {

                float result = 0;

                int j = firstNum.Length;

                for (int i = 0; i < j; i++)
                {

                    result += 1 - GetAbs(firstNum[i], scondNum[i]);

                }

                return result / j;

            }

        }


        /// <summary>
        ///  去掉杂点（适合杂点/杂线粗为1）
        /// </summary>
        /// <param name="dgGrayValue">背前景灰色界限</param>
        /// <returns></returns>
        public void ClearNoise(int dgGrayValue, int MaxNearPoints)
        {
            Color piexl;
            int nearDots = 0;
            int XSpan, YSpan, tmpX, tmpY;
            //逐点判断
            for (int i = 0; i < Im.Width; i++)
                for (int j = 0; j < Im.Height; j++)
                {
                    piexl = Im.GetPixel(i, j);
                    if (piexl.R < dgGrayValue)
                    {
                        nearDots = 0;
                        //判断周围8个点是否全为空
                        if (i == 0 || i == Im.Width - 1 || j == 0 || j == Im.Height - 1)  //边框全去掉
                        {
                            Im.SetPixel(i, j, Color.FromArgb(255, 255, 255));
                        }
                        else
                        {
                            if (Im.GetPixel(i - 1, j - 1).R < dgGrayValue) nearDots++;
                            if (Im.GetPixel(i, j - 1).R < dgGrayValue) nearDots++;
                            if (Im.GetPixel(i + 1, j - 1).R < dgGrayValue) nearDots++;
                            if (Im.GetPixel(i - 1, j).R < dgGrayValue) nearDots++;
                            if (Im.GetPixel(i + 1, j).R < dgGrayValue) nearDots++;
                            if (Im.GetPixel(i - 1, j + 1).R < dgGrayValue) nearDots++;
                            if (Im.GetPixel(i, j + 1).R < dgGrayValue) nearDots++;
                            if (Im.GetPixel(i + 1, j + 1).R < dgGrayValue) nearDots++;
                        }

                        if (nearDots < MaxNearPoints)
                            Im.SetPixel(i, j, Color.FromArgb(255, 255, 255));   //去掉单点 && 粗细小3邻边点
                    }
                    else  //背景
                        Im.SetPixel(i, j, Color.FromArgb(255, 255, 255));
                }
        }

        /// <summary>
        /// 改变大小
        /// </summary>
        /// <param name="bmp"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <returns></returns>
        public Bitmap ReSize(Bitmap bmp, int width, int height)
        {
            Bitmap newbmp = new Bitmap(bmp, width, height);
            return newbmp;
        }

        /// <summary>
        /// 黑白图片比较相似度
        /// </summary>
        /// <param name="e1"></param>
        /// <param name="e2"></param>
        /// <returns></returns>
        public double GetCosine(int[] e1, int[] e2)
        {
            int a = 0;//分母1
            int b = 0;//分母2
            int c = 0;//分子
            for (int y = 0; y < 32; ++y)
            {
                //两个数组中的整数按位与
                int i = e2[y] & e1[y];
                //按位加
                for (int x = 1; x < 33; ++x)
                {
                    c += (i >> x) & 1;
                    a += (e2[y] >> x) & 1;
                    b += (e1[y] >> x) & 1;
                }
            }
            //计算分母
            int d = a * b;
            return d == 0 ? 0 : c / Math.Sqrt(d);
        }

        public int GetBlackColCount(Bitmap bmp, int splitcol)
        {
            int count = 0;
            for (int i = 0; i < bmp.Height; i++)
            {
                if (bmp.GetPixel(splitcol, i).R != 255 && i == 0)
                {
                    count++;
                }
                else if (bmp.GetPixel(splitcol, i).R != 255 && bmp.GetPixel(splitcol, i-1).R == 255 && i > 0)
                {
                    count++;
                }
            }
            return count;
        }

        public int GetBlackRowCount(Bitmap bmp, int splitrow)
        {
            int count = 0;
            for (int i = 0; i < bmp.Width; i++)
            {
                if (bmp.GetPixel(i, splitrow).R != 255 && i == 0)
                {
                    count++;
                }
                else if (bmp.GetPixel(i, splitrow).R != 255 && bmp.GetPixel(i - 1, splitrow).R == 255 && i>0)
                {
                    count++;
                }
            }
            return count;
        }

        public int GetBlackCountRow(Bitmap bmm, int row)
        {
            int blackcount = 0;
            if (row == bmm.Width)
                return blackcount;
            for (int i = 0; i < bmm.Width; i++)
            {
                if (bmm.GetPixel(i, row).R != 255)
                    blackcount++;
            }
            return blackcount;
        }

        public int GetBlackCountcol(Bitmap bmm, int col)
        {
            int blackcount = 0;
            for (int i = 0; i < bmm.Height; i++)
            {
                if (bmm.GetPixel(col, i).R != 255)
                    blackcount++;
            }
            return blackcount;
        }

        /// <summary>
        /// 获取二进制数组
        /// </summary>
        /// <param name="bmp"></param>
        /// <returns></returns>
        public int[] GetIdentfiy(Bitmap bmp)
        {
            int[] result = new int[1024];
            for (int i = 0; i < bmp.Width; i++)
            {
                for (int j = 0; j < bmp.Height; j++)
                {
                    if (bmp.GetPixel(i, j).R == 255)
                        result[32 * i + j] = 0;
                    else
                        result[32 * i + j] = 1;
                }
            }
            return result;
        }

        /// <summary>
        /// 3×3中值滤波除杂，yuanbao,2007.10
        /// </summary>
        /// <param name="dgGrayValue"></param>
        public void ClearNoise(int dgGrayValue)
        {
            int x, y;
            byte[] p = new byte[9]; //最小处理窗口3*3
            byte s;
            //byte[] lpTemp=new BYTE[nByteWidth*nHeight];
            int i, j;

            //--!!!!!!!!!!!!!!下面开始窗口为3×3中值滤波!!!!!!!!!!!!!!!!
            for (y = 1; y < Im.Height - 1; y++) //--第一行和最后一行无法取窗口
            {
                for (x = 1; x < Im.Width - 1; x++)
                {
                    //取9个点的值
                    p[0] = Im.GetPixel(x - 1, y - 1).R;
                    p[1] = Im.GetPixel(x, y - 1).R;
                    p[2] = Im.GetPixel(x + 1, y - 1).R;
                    p[3] = Im.GetPixel(x - 1, y).R;
                    p[4] = Im.GetPixel(x, y).R;
                    p[5] = Im.GetPixel(x + 1, y).R;
                    p[6] = Im.GetPixel(x - 1, y + 1).R;
                    p[7] = Im.GetPixel(x, y + 1).R;
                    p[8] = Im.GetPixel(x + 1, y + 1).R;
                    //计算中值
                    for (j = 0; j < 5; j++)
                    {
                        for (i = j + 1; i < 9; i++)
                        {
                            if (p[j] > p[i])
                            {
                                s = p[j];
                                p[j] = p[i];
                                p[i] = s;
                            }
                        }
                    }
                    //      if (Im.GetPixel(x, y).R < dgGrayValue)
                    Im.SetPixel(x, y, Color.FromArgb(p[4], p[4], p[4]));    //给有效值付中值
                }
            }
        }
    }
}
